<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item>
          <el-select v-model="selectedRole" placeholder="用户角色" clearable style="width: 200px" class="filter-item">
            <el-option v-for="item in roles" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" style="width: 80px" type="primary" @click="handleFilter">
            筛选
          </el-button>
        </el-form-item>
        <el-form-item>
          <router-link :to="'/user/add'">
            <el-button style="width: 100px" type="success">
              添加用户
            </el-button>
          </router-link>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" min-width="50%">
        <template slot-scope="scope">
          {{ scope.$index+1 }}
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center" min-width="120%">
        <template slot-scope="scope">
          {{ scope.row.uid }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" min-width="120%">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center" min-width="150%">
        <template slot-scope="scope">
          {{ scope.row.department }}
        </template>
      </el-table-column>
      <el-table-column label="角色" align="center" min-width="120%">
        <template slot-scope="scope">
          <span>{{ scope.row.role }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" min-width="150%" align="center">
        <template slot-scope="scope">
          {{ scope.row.contact }}
        </template>
      </el-table-column>
      <el-table-column label="操作" class-name="status-col" align="center" min-width="150%">
        <template slot-scope="{row}">
          <el-button size="mini" type="success" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="primary" size="mini" @click="handleResetPassword(row)">
            重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />

    <el-dialog title="编辑用户信息" :visible.sync="dialogTableVisible" style="width: 90%; padding-left: 15%">
      <el-form label-width="70px" style="width: 60%; margin-left: 50px">
        <el-form-item label="用户名">
          <el-input v-model="tempInfo.uid" :disabled="true" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="tempInfo.name" />
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="tempInfo.department" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="tempInfo.role" placeholder="用户角色">
            <el-option v-for="role in roles" :key="role" :label="role" :value="role" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="tempInfo.contact" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" style="width: 100px" @click="handleUpdate">
          提交
        </el-button>
        <el-button @click="dialogTableVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="重置密码" :visible.sync="dialogFormVisible" style="width: 90%; padding-left: 15%">
      <el-form ref="pwdForm" :rules="pwdRules" :model="pwdForm" label-width="80px" style="width: 60%; margin-left: 50px">
        <el-form-item label="新密码" prop="password">
          <el-input ref="password" v-model="pwdForm.password" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="pwdcheck">
          <el-input ref="pwdcheck" v-model="pwdForm.pwdcheck" type="password" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" style="width: 100px" @click="handleReset">
          提交
        </el-button>
        <el-button @click="resetContent('pwdForm')">
          取消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, getUserListByRole, updateUserInfo, resetPassword } from '@/api/user'
import Pagination from '@/components/Pagination'

export default {
  components: { Pagination },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      }
      if (value.length < 6) {
        callback(new Error('密码长度至少6位'))
      } else {
        if (this.pwdForm.pwdcheck !== '') {
          this.$refs.pwdForm.validateField('pwdcheck')
        }
        callback()
      }
    }
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      }
      if (value.length < 6) {
        callback(new Error('密码长度至少6位'))
      }
      if (value !== this.pwdForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      pwdForm: {
        password: '',
        pwdcheck: '',
        uid: ''
      },
      pwdRules: {
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        pwdcheck: [{ required: true, trigger: 'blur', validator: validateConfirmPassword }]
      },
      roles: ['系统管理员', '学生', '校内老师', '企业导师'],
      list: null,
      listLoading: true,
      tempInfo: {
        uid: '',
        name: '',
        department: '',
        role: '',
        contact: ''
      },
      selectedRole: '',
      dialogTableVisible: false,
      dialogFormVisible: false
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getUserList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleEdit(row) {
      this.tempInfo = Object.assign({}, row)
      this.dialogTableVisible = true
    },
    handleFilter() {
      if (this.selectedRole === '') {
        getUserList(this.listQuery).then(response => {
          this.list = response.data.list
          this.total = response.data.total
          this.listLoading = false
        })
      } else {
        getUserListByRole(this.listQuery, this.selectedRole).then(response => {
          this.list = response.data.list
          this.total = response.data.total
          this.listLoading = false
        }).catch(() => {
          this.$message.error('获取用户信息错误')
        })
      }
    },
    handleUpdate() {
      updateUserInfo(this.tempInfo).then(() => {
        this.$message({
          message: '更新用户信息成功',
          type: 'success'
        })
        this.dialogTableVisible = false
        // this.$router.go(0) // 更新信息后刷新页面
        this.fetchData()
      }).catch(() => {
        this.$$message.error('更新用户信息失败')
      })
    },
    handleResetPassword(row) {
      this.pwdForm.uid = row.uid
      this.dialogFormVisible = true
    },
    handleReset() {
      this.$refs.pwdForm.validate(valid => {
        if (valid) {
          resetPassword(this.pwdForm).then(() => {
            this.$message({
              message: '重置密码成功',
              type: 'success'
            })
            this.dialogFormVisible = false
          }).catch(() => {
            this.$message.error('重置密码失败')
          })
        }
      })
    },
    resetContent(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>

.filter-container {
  margin-left: 20px;
}

</style>
